
let options = []
const maxlength = 50
const minInterval = 30
const minDelay = 30
let isClick = false

/**
 * @description: 获取插件配置信息
 * @return {*}
 */
async function getPluginInfo (){
    await sendMessage({type: 'getPluginInfo'}, (response) => {
        const {source, options: options_, inputData} = response
        options.splice(0)
        options.push(...options_)
        options_.forEach(item => {
            $('#reasonInput').append($(`<option value="${item.value}">${item.label}</option>`))
        });
        const {reason: reason = 0, desc: desc = '', interval: interval = 30, delay: delay = 30} = inputData
        $("#reasonInput").val(reason);
        $("#descInput").val(desc);
        $("#intervalInput").val(interval);
        $("#delayInput").val(delay);
        setTextareaLimit()
    })
}

/**
 * @description: 封装发送方法
 * @param {*} message
 * @param {*} callback
 * @return {*}
 */
function sendMessage(message, callback){
    return new Promise((resolve, reject)=>{
        try {
            chrome.tabs.query({currentWindow: true, active: true}, tabs => {
                chrome.tabs.sendMessage(tabs[0].id, message, (response) => {
                    callback && callback(response)
                    resolve(response)
                });
            });
        } catch (error) {
            reject(error)
        }
    })
}

/**
 * @description: 表单校验
 * @return {*}
 */
function validate (){
    let flag = true;
    let errArr = $(".err");
    for (let i = 0; i < errArr.length; i++) {
        errArr[i].innerHTML = "";
    }
    const reason = $('#reasonInput').val();
    const desc = $('#descInput').val();
    const interval = Number($('#intervalInput').val());
    const delay = Number($('#delayInput').val());

    if(options.find(item => item.value == reason).label === '其他' && !desc){
        errArr[2].innerHTML = "请输入申请描述";
        flag = false;
    }

    if (!interval) {
        errArr[3].innerHTML = "请设置申请间隔时间";
        flag = false;
    }
    if (interval && interval < minInterval) {
        errArr[3].innerHTML = `申请间隔时间需不小于${minInterval}秒~`;
        flag = false;
    }

    if (!delay) {
        errArr[4].innerHTML = "请设置申请超时后重试时间";
        flag = false;
    }
    if (delay && delay < minDelay) {
        errArr[4].innerHTML = `超时刷新时间需不小于${minDelay}秒~`;
        flag = false;
    }
    return flag;
}

/**
 * @description: 启动按钮点击事件
 * @return {*}
 */
function addSubmitListener(){
    $('#launch').click(async () => {
        if(validate()){
            if(isClick) return
            isClick = true
            const reason = $("#reasonInput").val();
            const desc = $("#descInput").val();
            const interval = Number($("#intervalInput").val());
            const delay = Number($("#delayInput").val());
            const data = {reason, desc, interval, delay}
            await sendMessage({type: 'launch', data}, (response) => {
                console.log('launch - -   response - - -      ', response)
            })
        }
    })
}

/**
 * @description: textarea input事件监听
 * @return {*}
 */
 function addTextareaInputListener(){
    $('#descInput').bind('input propertychange', val => {
        setTextareaLimit()
    })
}

/**
 * @description: 设置文本输入框的字数限制
 * @return {*}
 */
function setTextareaLimit(){
    const valll = $('#descInput').val()
        const limit = `${valll.length}/${maxlength}`
        $('#textareaLimit').text(limit)
}



document.addEventListener('DOMContentLoaded', async () => {
    await getPluginInfo()
    addSubmitListener()
    addTextareaInputListener()
})

